import {
	defineStore
} from 'pinia'
import {
	ref,
	reactive,
	computed
} from 'vue'
import http from '@/http'

export const useGlobalStore = defineStore('global', () => {

	const userInfo = ref(null)

	const setUserInfo = (info) => {
		userInfo.value = info
	}



	const getCode = (detail) => {
		uni.login({
			provider: 'weixin',
			success: (loginRes) => {
				console.log('loginRes', loginRes)
				uni.showToast({
					title: 'login'
				})
				http.post('/api/wechat-signin', {
					wechat_iv: detail.iv,
					wechat_encryted_data: detail.encryptedData,
					wechat_auth_code: loginRes.code
				}).then(signinRes => {
					uni.showToast({
						title: 'signin'
					})
					uni.setStorageSync('token', signinRes.data
						?.access_token)
					http.get('/api/user-selfinfo').then(selfinfoRes => {
						uni.showToast({
							title: 'selfinfo'
						})
						if (selfinfoRes.code === 0) {
							uni.getUserInfo({ // 拿取微信头像等信息

								success: (wxRes) => {
									uni.showToast({
										title: 'getUserInfo'
									})
									selfinfoRes.data.wxUserInfo =
										wxRes
										.userInfo
									setUserInfo(selfinfoRes.data)
									uni.setStorageSync(
										'userInfo', JSON
										.stringify(selfinfoRes
											.data
										) // 将微信头像等信息和接口返回的个人信息保存到pinia
									)
								}
							})
						}
					})
				})
			},
			fail: (err) => {
				console.log('登录失败:', err);
			}
		});
	}


	const safeArea = ref({})

	const setSafeArea = (data) => {
		safeArea.value = data
	}

	const padBottom = computed(() => {
		if (safeArea.value.paddingBottom) {
			return {
				paddingBottom: safeArea.value.paddingBottom + 'px'
			}
		} else {
			return {
				paddingBottom: 12 / 750 * safeArea.value.rightBorder + 'px'
			}
		}
	})

	const bottomSafePlus = (rpx) => { //底部安全区，底部还有自己的view的情况，参数rpx是自己view的高度
		if (safeArea.value.paddingBottom) {
			return {
				paddingBottom: (safeArea.value.paddingBottom + rpx / 750 * safeArea.value.rightBorder) +
					'px'
			}
		} else {
			return {
				paddingBottom: (12 / 750 * safeArea.value.rightBorder + rpx / 750 * safeArea.value
					.rightBorder) + 'px'
			}
		}
	}

	const curTabKey = ref("ticket")

	const tabClick = (key) => {
		curTabKey.value = key
	}

	const menuButton = ref({})

	const setMenuButton =(value) => {
		menuButton.value = value
	}



	return {
		userInfo,
		setUserInfo,
		getCode,
		safeArea,
		setSafeArea,
		padBottom,
		curTabKey,
		tabClick,
		bottomSafePlus,
		menuButton,
		setMenuButton
	};
});